<template>
  <el-dialog
    :title="type == 'add' ? '添加题库分类' : '修改题库分类'"
    v-model="visible"
    @close="handleClose"
  >
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="formRef"
      class="good-form"
      label-width="120px"
    >
      <el-form-item label="排序值" prop="classify_id">
        <el-input
          v-model="ruleForm.classify_id"
          style="width: 60%"
          :readonly="isReadOnly"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" style="width: 60%" />
      </el-form-item>
      <el-form-item label="展示图片" prop="src">
        <!--
                  :headers="{
                    token: token,
                  }"
                  action="http://localhost:3333/web_question/admin/upload"
                 -->
        <el-upload
          ref="pictureUpload"
          name="banner"
          class="avatar-uploader"
          accept="jpg,jpeg,png"
          list-type="picture-card"
          action="http://localhost:3333/web_question/admin/upload"
          :limit="1"
          :auto-upload="true"
          :before-upload="handleBeforeUpload"
          :on-success="handleUrlSuccess"
          :on-change="handleChange"
        >
          <el-icon><Plus /></el-icon>
          <template #file="{ file }">
            <div>
              <img
                class="el-upload-list__item-thumbnail"
                :src="file.url"
                alt=""
              />
              <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                  <el-icon><Delete /></el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload>
        <!-- <el-dialog v-model="dialogVisible">
                  <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog> -->
      </el-form-item>

      <el-form-item label="添加时间" prop="atime">
        <!-- <el-input v-model="ruleForm.atime" /> -->
        <el-date-picker
          v-model="ruleForm.atime"
          type="datetime"
          placeholder="添加时间"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { getClassify, addClassify, updateClassify } from "../../api/classify";
import { ElMessage } from "element-plus";
import {
  reactive,
  ref,
  toRefs,
  getCurrentInstance,
  // defineEmits,
  // defineProps,
  // defineExpose,
} from "vue";

const props = defineProps({
  type: String,
});

// import { localGet, uploadImgServer, hasEmoji } from "../utils";

const { proxy } = getCurrentInstance();
const pictureUpload = ref(null);
const isReadOnly = ref(false);
const formRef = ref(null);
const state = reactive({
  // uploadImgServer,
  // token: localGet("token") || "",
  visible: false,
  ruleForm: {
    classify_id: "",
    title: "",
    src: "",
    atime: "",
  },
  rules: {
    url: [{ required: "true", message: "图片不能为空", trigger: ["change"] }],
    sort: [{ required: "true", message: "排序不能为空", trigger: ["change"] }],
  },
  id: "",
});

const { visible, ruleForm, rules, id } = toRefs(state);

const handleRemove = (file) => {
  pictureUpload.value.handleRemove(file);
};
// 获取详情
const getDetail = (id) => {
  // axios.get(`/carousels/${id}`).then((res) => {
  //   state.ruleForm = {
  //     url: res.carouselUrl,
  //     link: res.redirectUrl,
  //     sort: res.carouselRank,
  //   };
  // });
};
const handleBeforeUpload = (file) => {
  const sufix = file.name.split(".")[1] || "";
  if (!["jpg", "jpeg", "png"].includes(sufix)) {
    ElMessage.error("请上传 jpg、jpeg、png 格式的图片");
    return false;
  }
};

const handleChange = (file) => {
  state.ruleForm.src = file;
};

// 上传图片
const handleUrlSuccess = (val) => {
  state.ruleForm.url = val.data || "";
};

// 开启弹窗
const open = (classify) => {
  // 开启弹窗
  state.visible = true;
  // 判断是添加还是修改
  if (classify) {
    // 修改
    state.ruleForm = {
      classify_id: classify.classify_id,
      title: classify.title,
      src: classify.src,
      atime: classify.atime,
    };
    isReadOnly.value = true;
  } else {
    // 添加
    state.ruleForm = {
      classify_id: "",
      title: "",
      src: "",
      atime: "",
    };
    isReadOnly.value = false;
  }
};
// 关闭弹窗
const close = () => {
  state.visible = false;
};
const handleClose = () => {
  formRef.value.resetFields();
};

const emit = defineEmits(["changeTableData"]);

// 点击确定
const submitForm = () => {
  // 判断是添加还是修改
  if (!isReadOnly.value) {
    addClassify(proxy, state.ruleForm)
      .then((data) => {
        // console.log(data);
        if (data.code === 200) {
          ElMessage({
            type: "success",
            message: data.msg,
          });
          getClassify(proxy).then((result) => {
            emit("changeTableData", result);
          });
        } else {
          ElMessage({
            type: "success",
            message: data.msg,
          });
        }
      })
      .catch((err) => {
        console.log(123123);
      });
  } else {
    updateClassify(proxy, state.ruleForm).then((data) => {
      if (data.code === 200) {
        getClassify(proxy).then((result) => {
          emit("changeTableData", result);
        });
      }
    });
  }
  // 关闭弹窗
  state.visible = false;
};

// 因为使用 script setup的组件是默认关闭的，也即通过模板 ref 或者 $parent 链获取到的组件的公开实例，不会暴露任何在 script setup 中声明的绑定。
// 为了在 script setup 组件中明确要暴露出去的属性，使用 defineExpose 编译器宏：
defineExpose({
  open,
});
</script>

<style scoped>
/* .avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}
.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
} */
</style>
